package com.kaesar.leetcode.LeetCode_100_150;

import com.kaesar.leetcode.TreeNode;

import java.util.*;

public class LeetCode_103 {
    public static List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        if (root == null) {
            return new ArrayList<>();
        }
        List<List<Integer>> result = new ArrayList<>();
        Queue<TreeNode> nodes = new LinkedList<>();
        nodes.add(root);
        // 当directionFlag为true时，从左往右放入节点；当directionFlag为false时，从右往左放入节点
        boolean directionFlag = true;
        while (!nodes.isEmpty()) {
            int count = nodes.size();
            List<Integer> vals = new ArrayList<>();
            Stack<TreeNode> temp = new Stack<>();
            while (count > 0) {
                TreeNode curNode = nodes.poll();
                vals.add(curNode.val);
                if (!directionFlag) {
                    if (curNode.right != null) {
                        temp.push(curNode.right);
                    }
                    if (curNode.left != null) {
                        temp.push(curNode.left);
                    }
                } else {
                    if (curNode.left != null) {
                        temp.push(curNode.left);
                    }
                    if (curNode.right != null) {
                        temp.push(curNode.right);
                    }
                }
                count--;
            }
            // 将栈中的节点取出放入队列中
            while (!temp.isEmpty()) {
                nodes.add(temp.pop());
            }
            // 每一层遍历后变更顺序
            directionFlag = !directionFlag;
            result.add(vals);
        }
        return result;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.right.right = new TreeNode(5);


        for (List<Integer> integers : zigzagLevelOrder(root)) {
            for (Integer integer : integers) {
                System.out.print(integer + " ");
            }
            System.out.println();
        }
    }
}
